package com.xzl.xep.dao.hibernate;

import java.util.Date;

import org.springframework.stereotype.Repository;

import com.xzl.xep.common.utils.DateUtil;
import com.xzl.xep.dao.ReportDao;
import com.xzl.xep.pojo.Payment;
import com.xzl.xep.pojo.ReportDto;

@Repository("reportDao")
public class HibernateReportDao extends HibernateDao implements ReportDao{

	@Override
	public ReportDto getTotalDto(Long companyId) {
		ReportDto dto = new ReportDto();
		dto.setCounts(this.getCustomerCounts(companyId, null, null));
		dto.setCredit(this.getCredit(companyId, null, null));
		dto.setCustomerSpend(this.getCustomerSpend(companyId, null, null));
		dto.setSpend(this.getSpend(companyId, null, null));
		
		return dto;
	}

	@Override
	public ReportDto getTodayDto(Long companyId) {
		ReportDto dto = new ReportDto();
		dto.setCounts(this.getCustomerCounts(companyId, DateUtil.getCurrentDate(), DateUtil.getCurrentDate()));
		dto.setCredit(this.getCredit(companyId, DateUtil.getCurrentDate(), DateUtil.getCurrentDate()));
		dto.setCustomerSpend(this.getCustomerSpend(companyId, DateUtil.getCurrentDate(), DateUtil.getCurrentDate()));
		dto.setSpend(this.getSpend(companyId, DateUtil.getCurrentDate(), DateUtil.getCurrentDate()));
		
		return dto;
	}

	@Override
	public Integer getCustomerCounts(Long companyId,Date start, Date end){
		
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from Customer where 1=1 ");
		append(sb, companyId, start,  end);
		
		return this.selectIntByHql(sb.toString());
	}
	
	@Override
	public Double getCustomerSpend(Long companyId,Date start, Date end){
		
		StringBuffer sb = new StringBuffer();
		sb.append("select sum(saleMoney) from Sale where 1=1 and isCustomer = 1 ");
		append(sb, companyId, start,  end);
		
		return this.selectDoubleByHql(sb.toString());
	}
	
	@Override
	public Double getCredit(Long companyId,Date start, Date end){
		
		StringBuffer sb = new StringBuffer();
		sb.append("select sum(creditMoney) from Payment where 1=1 and business = '").append(Payment.CREDIT_BUSINESS).append("'");
		append(sb, companyId, start,  end);
		
		return this.selectDoubleByHql(sb.toString());
	}

	@Override
	public Double getSpend(Long companyId,Date start, Date end){
		
		StringBuffer sb = new StringBuffer();
		sb.append("select sum(saleMoney) from Sale where 1=1 ");
		append(sb, companyId, start,  end);
		
		return this.selectDoubleByHql(sb.toString());
	}

	
	private void append(StringBuffer sb,Long companyId,Date start, Date end){
		if(companyId != null && companyId > 0)
			sb.append(" and companyId = ").append(companyId);
		
		if(start != null)
			sb.append(" and createTime >= '").append(DateUtil.dateFormate(start, "yyyy-MM-dd")).append(" 00:00:00' ");
		
		if(end != null)
			sb.append(" and createTime <= '").append(DateUtil.dateFormate(start, "yyyy-MM-dd")).append(" 23:59:59' ");
		
	}
}
